<?php
/**
 * 账单
 * @author solar
 */
class CheckoutProxy extends BaseProxy
{
	/**
	 * 已结账单记录
	 * @author solar
	 */
	public function history() {
		$validator=new Validator();
		$validator->setRule('group_id',array('账单组ID','required','int'=>array('isPositive'=>true)));
		$validation=$validator->validate($_GET);
		if($validation!==true) return $this->fail($validation);
		if(!ServiceFactory::get('GroupService')->hasPrivilege($_GET['group_id'])){
			return $this->fail('您不是账单组的成员，没有权限');
		}
		$checkoutModel=ModelFactory::get('CheckoutModel');
		$aWhere['g_id']=$_GET['group_id'];
		$aWhere['c_status']=1;
		$data['count']=$checkoutModel->getCount($aWhere);
		$data['list']=$checkoutModel->getList($this->getOffset(),$this->getLimit(),'c_id','DESC',$aWhere);
		return $this->success($data);
	}
	
	/**
	 * 账单汇总
	 * @author solar
	 */
	public function summary() {
		$validator=new Validator();
		$validator->setRule('checkout_id',array('账单ID','required','int'=>array('isPositive'=>true)));
		$validation=$validator->validate($_GET);
		if($validation!==true) return $this->fail($validation);
		$checkoutRow=ModelFactory::get('CheckoutModel')->get($_GET['checkout_id']);
		if(!$checkoutRow) return $this->fail('找不到账单');
		if(!ServiceFactory::get('GroupService')->hasPrivilege($checkoutRow['g_id'])){
			return $this->fail('您不是账单组的成员，没有权限');
		}
		$data['checkout']=$checkoutRow;
		$data['co_users']=ModelFactory::get('CheckoutUserModel')->getAll(array('c_id'=>$_GET['checkout_id']));
		return $this->success($data);
	}
	
	/**
	 * 结账
	 * @author solar
	 */
	public function checkout() {
		$validator=new Validator();
		$validator->setRule('checkout_id',array('账单ID','required','int'=>array('isPositive'=>true)));
		$validation=$validator->validate($_POST);
		if($validation!==true) return $this->fail($validation);
		$checkoutModel=ModelFactory::get('CheckoutModel');
		$checkoutRow=$checkoutModel->get($_POST['checkout_id']);
		if(!$checkoutRow) return $this->fail('找不到账单');
		if($checkoutRow['c_status']==1) return $this->fail('账单已经是结账状态');
		if(!ModelFactory::get('BillModel')->hasBill($_POST['checkout_id'])){
			return $this->fail('账单中没有任何记录，无法结账');
		}
		if(!$checkoutModel->close($_POST['checkout_id'])){
			return $this->error(Gateway::InternalError);
		}
		$c_id = $checkoutModel->newCheckout($checkoutRow['g_id']);
		if(!$c_id) return $this->error(Gateway::InternalError);
		return $this->success(array('c_id'=>$c_id));
	}
}
